package cn.anxin.a9.libice;

import android.content.Context;

import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("unused, JniMissingFunction")
public class LibIce {
    private static boolean sLoaded = false;

    private List<IceTransListener> listeners;

    //used by jni begin
    private long native_data;
    //used by jni end

    public LibIce() {
//        loadLibraries();
        nativeNew();
        listeners = new ArrayList();
    }

    public static synchronized void loadLibraries() {
        if (sLoaded)
            return;

        //ice jni
        System.loadLibrary("icejni");
        sLoaded = true;
    }

    /*
     * op
     *  "initialization",
     *  "negotiation",
     *  "op_keep_alive",
     *  "op_addr_change",
     *  "unknown_op"
     * status
     *  0 SUCCESS
     */
    private void onComplete(int op, int status) {
        for (IceTransListener listener : listeners) {
            listener.onComplete(op, status);
        }
    }

    private void onRxData(int op, String addr, int type, byte[] data) {
        for (IceTransListener listener : listeners) {
            listener.onRxData(op, addr, type, data);
        }
    }

    protected void finalize() throws Throwable {
        this.nativeFinalize();
        super.finalize();
    }

    public void addListener(IceTransListener listener) {
        listeners.add(listener);
    }

    private native void nativeNew();

    public native int create(String stunServerAddr, String turnServerAddr, String username, String password);

    public native String getSdp();

    public native int start(String sdp, String client);

    public native void destroy();

    public native int initRtpSocket(String addr, int vport, int aport);

    public native int sendPCM(byte[] buf, int len);

    public native int sendPCM(short[] buf, int len);

    public native void nativeFinalize();

    public native void addTarget(Object target);

    public native void setTimeout(int msec);

    public native void setPeerSourceReportInterval(int msec);

    public native void setDropFrame(int dropFrame);

    static {
        loadLibraries();
    }

}